<%@page language="java" isELIgnored="false" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<jsp:directive.include file="/WEB-INF/sitemesh-decorators/include.jsp" />
<c:set var="menu" value="user" scope="request" />

<html>
<head>
<title>Users</title>
<script type="text/javascript">
   $(document).ready(function () {
      $("#btnUpdatePermission").jqxButton({ theme: getSowTheme('ui-redmond') });
      $("#btnUpdateUserGroup").jqxButton({ theme: getSowTheme('ui-redmond') });
      makeCenter2("ajax-loader");
      makeCenter("loading");
      $('#ajax-loader').hide();
      
      var source = {
         datatype: "json",
         datafields: [
			{ name: 'id' },
            { name: 'name' },
            { name: 'desc' },
            { name: 'checked' }
         ],
         id: 'id',
         url: "<c:url value='/admin/user/${id}/groups' />",
         async: false
      };

      var dataAdapter = new $.jqx.dataAdapter(source);

      $("#groupListbox").jqxListBox({ source: dataAdapter, displayMember: "name", valueMember: "id", checkboxes: true, width: 228, height: 250, theme: getTheme() });

      for(var i = 0; i < dataAdapter.records.length; i++) {
         if(dataAdapter.records[i].checked == "true") {
            $("#groupListbox").jqxListBox('checkIndex', i);
         }
      }

      $("#groupListbox").bind('select', function (event) {
         $("#groupDesc").html(dataAdapter.records[event.args.index].desc + "&nbsp;");
      });
      
   });
   
   function openMessageDiaglog(message) {
      $('#spanMessage').text(message);
      $("#dialog-message").dialog({
         resizable: false,
         draggable: false,
         modal: true,
         buttons: {
   			Ok: function() {
   				$(this).dialog("close");
   			}
         }
      });
   }

   function updateUserGroups() {
      var items = $("#groupListbox").jqxListBox('getCheckedItems');
      var groupIds = [];
      for(var i = 0; i < items.length; i++) {
         groupIds[i] = items[i].value;
      }

      $.ajax({
         url : "<c:url value='/admin/user/${id}/groups/update' />",
         type : "POST",
         data : { groupIds: groupIds },
         beforeSend : function() {
            $('#loading').show();
         },
         complete : function() {
            $('#loading').hide();
         },
         success : function(data) {
            openMessageDiaglog("The user's groups have been updated successfully.");
         }
      });
   }

   function updatePermissions() {
      $.ajax({
         url : "<c:url value='/admin/user/${id}/permissions/update' />",
         type : "POST",
         data: $('#permissionForm').serialize(),
         beforeSend : function() {
            $('#ajax-loader').show();
         },
         complete : function() {
            $('#ajax-loader').hide();
         },
         success : function(data) {
            openMessageDiaglog("The user's permissions have been updated successfully.");
         },
         error : function() {
            alert("Failure args: " + arguments);
         }
      });
   }

   function updateProfile() {
      $.ajax({
         url : "<c:url value='/ajax/admin/user/profile/update' />",
         type : "POST",
         data: $('#profileForm').serialize(),
         dataType : "html",
         success : function(data) {
            $("#userProfile").html(data);
            if($(data).first().attr("id") != "error") {
            	openMessageDiaglog("The user's profile have been updated successfully.");
            }
         }
      });
   }

   function selectAll(perm) {
      var list = $("input:checkbox[name='" + perm + "']");
      var checked = false;

      list.each(function (index, element) {
         if(!$(element).attr('checked')) {
            checked = true;
         }
      });

      list.each(function (index, element) {
         $(element).attr('checked', checked);
      });
   }
</script>

<link rel="stylesheet" href="<c:url value='/css/PermissionsPanel.css' />" />
</head>

<body>
   <div class="cubeTitleWrapper">
      <span class="cube_title">User</span>
   </div>

   <div class="cube">
      <div>
         <div class="contentwrapper">
            <div class="contentcolumn">
               <div class="innertube">
                  <h2 class="userDefinedBg curved">User Profile</h2>
                  <div class="contentBlock">
                     <div id="userProfile"><jsp:directive.include file="/WEB-INF/pages/controls/user_profile_form.jsp" /></div>
                  </div>
                  <div class="contentBlock_bottom"><span class="right_end"><span></span></span></div>

                  <h2 class="userDefinedBg curved">Permission</h2>
                  <div class="contentBlock">
                     <div id="ajax-loader" style="position: absolute;"><img src="<c:url value='/images/ajax-loader.gif' />" /></div>
                     <form id="permissionForm"><input type="hidden" name="test" value="P">
                     <div class="permissionsPanel">
                        <div class="permissionTableHeader">
                           <table>
                              <thead>
                                 <tr class="head">
                                    <th><h3 style="cursor: text;">Document Repositories</h3></th>
                                    <td><span style="cursor: text;">Read</span></td>
                                    <td><span style="cursor: text;">&nbsp;</span></td>
                                    <td><span style="cursor: text;">Write</span></td>
                                    <td><span style="cursor: text;">&nbsp;</span></td>
                                    <td><span style="cursor: text;">Admin</span></td>
                                 </tr>
                              </thead>
                           </table>
                        </div>
                        <div class="permissionTable">
                           <table>
                              <thead>
                                 <tr class="head">
                                    <th><h3 style="cursor: text;"><span>Repository</span><span class="arrow"></span></h3></th>
                                    <td onclick="selectAll('reads')"><span title="Select all"></span></td>
                                    <td>&nbsp;</td>
                                    <td onclick="selectAll('writes')"><span title="Select all"></span></td>
                                    <td>&nbsp;</td>
                                    <td onclick="selectAll('admins')"><span title="Select all"></span></td>
                                 </tr>
                              </thead>
                              <tbody>
                                 <c:forEach items="${repositories}" var="repository" varStatus="i">
                                 <tr style="${i.count % 2 == 0 ? 'background: #efefef;' : ''}" class="accessRight">
                                    <th><span>${repository.name}</span><input type="hidden" name="repositoryIds" value="${repository.id}"></th>
                                    <td title="Read"><input type="checkbox" name="reads" value="${repository.id}" ${repository.read ? 'checked="checked"' : ''}></td>
                                    <td><span>&nbsp;</span></td>
                                    <td title="Write"><input type="checkbox" name="writes" value="${repository.id}" ${repository.write ? 'checked="checked"' : ''}></td>
                                    <td><span>&nbsp;</span></td>
                                    <td title="Admin"><input type="checkbox" name="admins" value="${repository.id}" ${repository.admin ? 'checked="checked"' : ''}></td>
                                 </tr>
                                 </c:forEach>
                              </tbody>
                           </table>
                        </div>
                        
                        <br>
                        <div align="right"><input id="btnUpdatePermission" type="button" value="Update" onclick="updatePermissions()" style="cursor: pointer;" /></div>
                     </div>
                     </form>
                  </div>
                  <div class="contentBlock_bottom"><span class="right_end"><span></span></span></div>
               </div>
            </div>
         </div>

         <div class="rightcolumn">
            <div class="innertube">
               <h2 class="userDefinedBg"><span class="right_end"><span class="start">Groups</span></span></h2>
               <div class="contentBlock">
                  <div id="groupListbox"></div>
                  <div id="groupDesc" style="padding-top: 10px"></div>
                  <div style="height: 30px; vertical-align:middle;">
                     <div id="loading" style="width:30px; float:left; display:none;"><img width="30px" src="<c:url value='/images/spinner.gif' />" /></div>
                     <div align="right" style="width:80px; float:right;"><input id="btnUpdateUserGroup" type="button" value="Update" onclick="updateUserGroups()" style="cursor: pointer;" /></div>
                  </div>
               </div>
               <div class="contentBlock_bottom"><span class="right_end"><span></span></span></div>
            </div>
         </div>
      </div>
   </div>
   
   <div id="dialog-message" title="Update success" style="display: none;">
      <p><span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 15px 0;"></span><span id="spanMessage">The user's permissions have been updated successfully.</span></p>
   </div>
</body>
</html>